import logging
import platform
import os
import threading
import subprocess
import sys
import importlib.util

import numpy as np

def play_notification_sound():
    """播放提示音"""
    try:
        # Windows系统
        if platform.system() == "Windows":
            import winsound
            winsound.Beep(1000, 200)  # 1000Hz, 200ms
            
        # macOS系统
        elif platform.system() == "Darwin":
            os.system('afplay /System/Library/Sounds/Ping.aiff')
            
        # Linux系统
        else:
            os.system('aplay -q /usr/share/sounds/speech-dispatcher/test.wav')
            
    except Exception as e:
        logging.error(f"无法播放提示音: {str(e)}")

def run_in_thread(target):
    """在新线程中运行函数"""
    thread = threading.Thread(target=target, daemon=True)
    thread.start()
    return thread

def calculate_rms(audio_data):
    """计算音频的RMS值"""
    if len(audio_data) > 0:
        squared = np.square(audio_data.astype(np.float32))
        mean_val = np.mean(squared)
        return np.sqrt(mean_val) if mean_val > 0 else 0
    return 0

def min_max_scaled(value, min_val, max_val):
    """限制值在指定范围内"""
    return max(min_val, min(max_val, value))

def check_and_install_dependencies():
    """检查并安装缺失的依赖项"""
    required_packages = {
        "PyQt5": "PyQt5",
        "numpy": "numpy",
        "websockets": "websockets",
        "pyaudio": "pyaudio",
        "requests": "requests",
        "psutil": "psutil",
        "pycaw": "pycaw"  # Windows音量控制
    }
    
    missing_packages = []
    
    for package_name, pip_name in required_packages.items():
        if importlib.util.find_spec(package_name) is None:
            missing_packages.append(pip_name)
    
    if missing_packages:
        logger = logging.getLogger("com_utils")
        logger.info(f"检测到缺失的依赖项: {', '.join(missing_packages)}")
        
        try:
            for package in missing_packages:
                logger.info(f"正在安装 {package}...")
                subprocess.check_call([sys.executable, "-m", "pip", "install", package])
                logger.info(f"{package} 安装成功")
        except subprocess.CalledProcessError as e:
            logger.error(f"安装依赖项失败: {str(e)}")
            return False
    
    return True